package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.DateUtil
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoCostService
import com.yige.service.mongoService.MongoLessonStuService
import com.yige.service.mongoService.MongoRecordService
import com.yige.service.mongoService.MongoSalaryService
import com.yige.service.mongoService.MongoStudentService
import com.yige.service.mongoService.MongoTeacherService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

/**
 * Created by sunhao on 2015/9/29 0029.
 */

@Controller
@RequestMapping("cost")
class CostController {

    @Autowired
    MongoCostService costService
    @Autowired
    MongoStudentService studentService
    @Autowired
    MongoTeacherService teacherService
    @Autowired
    MongoLessonStuService lessonService
    @Autowired
    MongoRecordService recordService
    @Autowired
    MongoSalaryService salaryService

    /*************控制器模块************/

    /**
     * 课费管理列表
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    def list(Model model) {
        List<DBObject> costList = costService.findListDescendingByDate()
        costArg(model, costList)
        select(model)
        return "cost/list"
    }

    /**
     * 多条件联合查询课费信息
     * @param model
     * @param studentId
     * @param teacherId
     * @param pay
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("find")
    def find(Model model, String studentId, String teacherId, Double pay, String startDate, String endDate) {
        def query = new BasicDBObject()
        if (!StringUtils.isEmpty(studentId)) {
            query.append("student", studentId)
        }
        if (!StringUtils.isEmpty(teacherId)) {
            query.append("teacher", teacherId)
        }
        if (pay != null) {
            query.append("pay", pay)
        }
        if (!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
            query.append("date", [$gte: DateUtil.parseDate(startDate), $lte: DateUtil.parseDate(endDate)] as BasicDBObject)
        }
        def costList = costService.findListByQueryDesDate(query) as LinkedList
        costArg(model, costList)
        select(model)
        return "cost/list"
    }

    /**
     * 计算教师工资
     * @param model
     * @param teacherId
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("salary")
    def teacherSalary(Model model, String teacher, String startDate, String endDate) {
        if (!StringUtils.isEmpty(teacher) && !StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
            def query = new BasicDBObject()
            query.append("teacher", teacher).append("date", [$gte: DateUtil.parseDate(startDate), $lte: DateUtil.parseDate(endDate)] as BasicDBObject)
            def costList = costService.findListByQuery(query) as ArrayList
            Double count = 0.0
            costList.each {
                count = count + it.pay
            }
            def salary = [_id    : UUID.randomUUID().toString(),
                          teacher: teacher,
                          status : 1,
                          pay    : Math.rint(count * SystemConstant.SALARY_SEVEN),
                          info   : startDate + "至" + endDate] as BasicDBObject
            salaryService.insertOne(salary)
            Map<String, Object> salaryInfo = new HashMap<>()
            salaryInfo.put("teacher", teacher)
            salaryInfo.put("pay", Math.rint(count * SystemConstant.SALARY_SEVEN))
            salaryInfo.put("startDate", startDate)
            salaryInfo.put("endDate", endDate)
            model.addAttribute("salary", salaryInfo)
            costArg(model, costList)
            select(model)
        }
        return "cost/list"
    }

    /**
     * 添加课费信息
     * @param teacher
     * @param student
     * @param date
     * @param pay
     * @return
     */
    @RequestMapping("addCost")
    @ResponseBody
    def addCost(String teacher, String student, String lesson, String date, Double pay) {
        Map<String, DBObject> costInfo = [_id    : UUID.randomUUID().toString(),
                                          teacher: teacher,
                                          student: student,
                                          lesson : lesson,
                                          pay    : pay]
        DBObject dbObject = ToDBObjectUtil.toDBObject(costInfo)
        boolean flag = saveCost(dbObject, date)
        def student_db = studentService.findOneById(student), list = new ArrayList(), ns
        student_db.lessons.each {
            if (lesson.equals(it.id)) {
                ns = it.n - 1
                it = [id: it.id, name: it.name, price: it.price, n: ns] as BasicDBObject
            }
            list.add(it)
        }
        studentService.updateLessonForStudent(student, list)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除课费信息
     * @param _ids
     * @return
     */
    @RequestMapping("delCost")
    @ResponseBody
    def delCost(@RequestParam('_ids') List<String> _ids) {
        boolean flag = false
        _ids.each { _id ->
            flag = costService.deleteOne(_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 修改课费信息
     * @param _id
     * @param teacher
     * @param student
     * @param date
     * @param pay
     * @return
     */
    @RequestMapping("updateCost")
    @ResponseBody
    def update(String _id, String teacher, String student, String lesson, String date, Double pay) {
        DBObject cost_db = costService.findOneById(_id)
        Date date_db
        if (date == "") {
            date_db = cost_db.date
        } else {
            date_db = DateUtil.parseDate(date)
        }
        Map<String, DBObject> costInfo = [_id    : _id,
                                          teacher: teacher,
                                          student: student,
                                          lesson : lesson,
                                          pay    : pay]
        DBObject dbObject = ToDBObjectUtil.toDBObject(costInfo)
        dbObject.put("date", date_db)
        boolean flag = costService.updateOne(_id, dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 计算大课工资
     * @param model
     * @param teacherId
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("salaryBig")
    def teacherSalaryBig(Model model, String teacher, String startDate, String endDate) {
        def query = new BasicDBObject()
        if (!StringUtils.isEmpty(teacher) && !StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
            query.append("teacher", teacher).append("date", [$gte: DateUtil.parseDate(startDate), $lte: DateUtil.parseDate(endDate)] as BasicDBObject)
            def costList = costService.findListByQuery(query) as ArrayList
            def set = new HashSet()
            costList.each {
                set.add(DateUtil.formatDate(it.date).equals())
            }
            int n = set.size()
            def salary
            if (teacher.equals("fd1511b8-0fb8-477d-9115-d85c1b266254")) {
                salary = n * 150
            }
            if (teacher.equals("cbc30f0c-1315-4aa4-9be6-42932a45e412")) {
                salary = n * 120
            }
            Map<String, Object> salaryInfo = new HashMap<>()
            salaryInfo.put("teacher", teacher)
            salaryInfo.put("pay", salary)
            salaryInfo.put("startDate", startDate)
            salaryInfo.put("endDate", endDate)
            model.addAttribute("salary", salaryInfo)
            costArg(model, costList)
            select(model)
        }
        return "cost/list"
    }

    /**
     * 添加大课课费
     * @param teacher
     * @param lesson
     * @param pay
     * @param date
     * @return
     */
    @RequestMapping("addBigCost")
    def addBigCost(String teacher, String lesson, double pay, String date) {
        def studentList = lessonService.findStuForLesson(lesson, teacher), list = new ArrayList()
        def costInfo, ns
        boolean flag = false
        studentList.each { student ->
            costInfo = [_id: UUID.randomUUID().toString(), student: student._id, teacher: teacher, lesson: lesson, pay: pay] as BasicDBObject
            flag = saveCost(costInfo, date)
            student.lessons.each {
                if (lesson.equals(it.id)) {
                    ns = it.n - 1
                    it = [id: it.id, name: it.name, price: it.price, n: ns] as BasicDBObject
                }
                list.add(it)

                flag = studentService.updateLessonForStudent(student._id, list)
                list = new ArrayList()
            }
            return ResultUtil.recallAjax(flag)
        }
    }

    @RequestMapping("findStuByTeacher")
    @ResponseBody
    def findStuByTeacher(String teacherId){
        def list = new ArrayList()
        def studentIds = teacherService.findAllStudentForTeacher(teacherId)
        studentIds.each {
            list.add([id: it, name: this.studentService.findOneById(it).name] as HashMap)
        }
        return [code: true, data: list]
    }

    /*************方法模块***************/

    def saveCost(DBObject costInfo, String date) {
        ArgsUtil.checkArgs(costInfo)
        DBObject cost_db = costService.findOneById(costInfo._id)
        if (cost_db == null) {
            costInfo.put("date", DateUtil.parseDate(date))
            costService.insertOne(costInfo)
            return true
        } else {
            return false
        }
    }

    def select(Model model) {
        List<DBObject> teacherList = teacherService.findList(),
                       studentList = studentService.findList(),
                       lessonList = lessonService.findList()
        model.addAttribute("teachers", teacherList)
        model.addAttribute("students", studentList)
        model.addAttribute("lessons", lessonList)
    }

    def costArg(Model model, List<DBObject> costList) {
        DBObject teacher, student, lesson
        List<Map<String, Object>> costMaps = new ArrayList<>()
        Map<String, Object> costMap = new HashMap<>()
        costList.each {
            teacher = teacherService.findOneById(it.teacher)
            student = studentService.findOneById(it.student)
            lesson = lessonService.findOneById(it.lesson)
            costMap.put("_id", it._id)
            costMap.put("date", DateUtil.formatDate(it.date as Date))
            costMap.put("student", student.name)
            costMap.put("teacher", teacher.name)
            costMap.put("lesson", lesson.name)
            costMap.put("pay", it.pay)
            costMaps.add(costMap)
            costMap = new HashMap<>()
        }
        model.addAttribute("costs", costMaps)
    }

}